package com.ruoyi.swla2.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.swla2.constant.ZoneLevelType;
import com.ruoyi.swla2.domain.TerminalsXb;
import com.ruoyi.swla2.domain.Zone;
import com.ruoyi.swla2.model.ZoneBuildingTAndM;
import com.ruoyi.swla2.model.ZoneJoinModel;
import com.ruoyi.swla2.service.ITerminalsXbService;
import com.ruoyi.swla2.service.IZoneJoinService;
import com.ruoyi.swla2.service.IZoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 区域管理Controller
 *
 * @author gdqt
 * @date 2023-06-16
 */
@RestController
@RequestMapping("/region/zone")
public class ZoneController extends BaseController {
    @Autowired
    private IZoneService zoneService;

    @Autowired
    private IZoneJoinService zoneJoinService;

    @Autowired
    private ITerminalsXbService terminalsXbService;

    /**
     * 查询区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('region:zone:list')")
    @GetMapping("/list")
//    public TableDataInfo list(Zone zone) {
    public List<Tree<String>> list(Zone zone) {
//        startPage();
        List<Zone> list = zoneService.selectZoneList(zone);
//        return getDataTable(list);
        return transformToTreeList(list);
    }

    /**
     * 导出区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('region:zone:export')")
    @Log(title = "区域管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Zone zone) {
        List<Zone> list = zoneService.selectZoneList(zone);
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(item -> item.setLevelType(ZoneLevelType.getLevelTypeName(item.getLevelType())));
        }
        ExcelUtil<Zone> util = new ExcelUtil<Zone>(Zone.class);
        util.exportExcel(response, list, "区域管理数据");
    }

    /**
     * 获取区域管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('region:zone:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long ID) {
        return success(zoneService.selectZoneByID(ID));
    }

    @PreAuthorize("@ss.hasPermi('region:zone:query')")
    @GetMapping(value = "/getBuildingTerminalsAndMeters")
    public AjaxResult getBuildingTerminalsAndMeters(@RequestParam("areaId") String areaId) {
        List<ZoneBuildingTAndM> result = zoneService.getBuildingTerminalsAndMeters(areaId);
        if (CollUtil.isNotEmpty(result)) {
            result.forEach(zone -> {
                ZoneJoinModel model = new ZoneJoinModel();
                model.setAreaId(zone.getAreaId());
                model.setTerminalMark(1);
                List<ZoneJoinModel> zoneJoinModels = zoneJoinService.getZoneJoinTerminals(model);
                zone.setTerminalsCount(zoneJoinModels.size());

                TerminalsXb terminalsXb = new TerminalsXb();
                terminalsXb.setAreaID(zone.getAreaId());
                terminalsXb.setTerminalMark(1L);
                List<TerminalsXb> terminalsXbList = terminalsXbService.selectTerminalsXbList(terminalsXb);
                zone.setMetersCount(terminalsXbList.size());
            });
        }
        return success(result);
    }

    /**
     * 新增区域管理
     */
    @PreAuthorize("@ss.hasPermi('region:zone:add')")
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Zone zone) {
        zone.setTenantId(this.getTenantId());
        zone.setPID(StrUtil.isEmpty(zone.getPID()) ? "root" : zone.getPID());
        return toAjax(zoneService.insertZone(zone));
    }

    /**
     * 修改区域管理
     */
    @PreAuthorize("@ss.hasPermi('region:zone:edit')")
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Zone zone) {
        return toAjax(zoneService.updateZone(zone));
    }

    /**
     * 删除区域管理
     */
    @PreAuthorize("@ss.hasPermi('region:zone:remove')")
    @Log(title = "区域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable Long[] IDs) {
        return toAjax(zoneService.deleteZoneByIDs(IDs));
    }

    private List<Tree<String>> transformToTreeList(List<Zone> nodeList) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("areaId");
        treeNodeConfig.setParentIdKey("pid");
        treeNodeConfig.setChildrenKey("children");
        treeNodeConfig.setWeightKey("rank");
        String[] levelTypeNames = {"大分区", "DMA", "大用户", "楼栋", "虚拟分区"};

        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "root", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getID().toString());
                    tree.setParentId(treeNode.getPID());
                    tree.setName(treeNode.getAreaName());
                    tree.putExtra("id", treeNode.getID());
                    tree.putExtra("tenantId", treeNode.getTenantId());
                    tree.putExtra("areaId", treeNode.getAreaID());
                    tree.putExtra("areaName", treeNode.getAreaName());
                    tree.putExtra("levelType", treeNode.getLevelType());
                    tree.putExtra("levelTypeName", levelTypeNames[Integer.parseInt(treeNode.getLevelType()) - 1]);
                    tree.putExtra("remark", treeNode.getRemark());
                    tree.putExtra("rank", treeNode.getRank());
                    tree.putExtra("zoom", treeNode.getZoom());
                    tree.putExtra("areaPoint", treeNode.getAreaPoint());
                    tree.putExtra("details", treeNode.getDetails());
                });

        return treeNodes;
    }
}
